package com.sysef.dao;

import java.lang.annotation.Annotation;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.lang.StringUtils;

import com.sysef.exception.DAOException;
import com.sysef.util.ConexionBD;
import com.sysef.util.DAOannotation;

public class BaseDAO {
	
	private static String SCHEMA = "sysef";

	protected void cerrarConexion(Connection con) throws RuntimeException {
		try {
			if (con != null && !con.isClosed()) {
				con.close();
			}
		} catch (SQLException se) {
			System.err.println("Error: cerrarConexion: " + se);
		}
	}

	protected void cerrarResultSet(ResultSet rs) throws RuntimeException {
		try {
			if (rs != null) {
				rs.close();
			}
		} catch (SQLException se) {
			System.err.println("Error: cerrarResultSet: " + se);
		}
	}

	protected void cerrarStatement(PreparedStatement stmt) throws RuntimeException {
		try {
			if (stmt != null) {
				stmt.close();
			}
		} catch (SQLException se) {
			System.err.println("Error: cerrarStatement: " + se);
		}
	}

	protected void cerrarCallable(CallableStatement callstmt) throws RuntimeException {
		try {
			if (callstmt != null) {
				callstmt.close();
			}
		} catch (SQLException se) {
			System.err.println("Error: cerrarCallable: " + se);
		}
	}

	public <T> T getByIdA(Integer id, Class<T> clase) throws DAOException {
		String claseStr = null;
		String dao = null;
		String table = null;
		Class<?> daoClass = null;

		if (clase == null) {
			throw new DAOException("clase es null");
		}

		claseStr = clase.getCanonicalName();

		if (StringUtils.isBlank(claseStr)) {
			throw new DAOException("clase no tiene canonicalName");
		}

		if (StringUtils.isBlank(claseStr)) {
			throw new DAOException("clase no tiene canonicalName");
		}

		Annotation annotation = clase.getAnnotation(DAOannotation.class);
		if (annotation instanceof DAOannotation) {
			DAOannotation daoAnnotation = (DAOannotation) annotation;
			dao = daoAnnotation.dao();
			table = daoAnnotation.table();
			if (!StringUtils.isBlank(dao)) {
				try {
					daoClass = Class.forName(dao);
				} catch (Exception ex) {
					throw new DAOException("la clase '" + dao + "' no existe'");
				}
			} else {
				throw new DAOException("@DAOannotation dao= 'vacio o no existe'");
			}
			if (!StringUtils.isBlank(table)) {
				if (existTable(table) <= 0) {
					throw new DAOException("@DAOannotation table=" + table + " 'la tabla no existe'");
				}
			} else {
				throw new DAOException("@DAOannotation table= 'vacio o no existe'");
			}
		} else {
			throw new DAOException("clase no tiene la anotacion @DAOannotation");
		}
		
		
		

		/*
		 * BeanTipoUsuario objBeanTipoUsuario = null; Connection con = null;
		 * PreparedStatement stmt = null; ResultSet rs = null; String query =
		 * "select * from usuario where idTipoUsuario=? and activo='true' order by idTipoUsuario"
		 * ;
		 * 
		 * try { con = ConexionBD.obtenerConexion(); stmt =
		 * con.prepareStatement(query); stmt.setInt(1, idTipoUsuario); rs =
		 * stmt.executeQuery(); if (rs.next()) { objBeanTipoUsuario = new
		 * BeanTipoUsuario();
		 * objBeanTipoUsuario.setIdTipoUsuario(DaoTools.getInteger(rs,
		 * "idTipoUsuario"));
		 * objBeanTipoUsuario.setNombre(rs.getString("nombre"));
		 * objBeanTipoUsuario.setDescripcion(rs.getString("descripcion"));
		 * objBeanTipoUsuario.setNivel(DaoTools.getInteger(rs, "nivel"));
		 * objBeanTipoUsuario.setActivo(DaoTools.getBoolean(rs, "activo")); } }
		 * catch (SQLException e) { System.err.println(e.getMessage()); throw
		 * new DAOExcepcion(e.getMessage()); } finally {
		 * this.cerrarResultSet(rs); this.cerrarStatement(stmt);
		 * this.cerrarConexion(con); } return objBeanTipoUsuario;
		 */
		return null;
	}

	private int existTable(String tableName) throws DAOException {
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		String query = "select count(*) from information_schema.tables where table_schema = '"+SCHEMA+"' and table_name = ?";
		int cantidad = 0;
		try {
			con = ConexionBD.obtenerConexion();
			stmt = con.prepareStatement(query);
			stmt.setString(1, tableName);
			rs = stmt.executeQuery();
			while (rs.next()) {
				cantidad = rs.getInt(1);
			}
		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOException(e.getMessage());
		} finally {
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		return cantidad;
	}

}
